package b2.widget
{
	import b2.scene.*;
	import b2.util.*;
	import b2.widget.fort.FortressDialog;
	import b2.widget.room.RoomDialog;
	import b2.widget.tech.TechTower;
	
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	
	public class WidgetManager
	{
		static private var instance:WidgetManager;
		public var exclusiveWidgets:Array;
		public var mouseOverMessage:Sprite;
		
		public function WidgetManager()
		{
			exclusiveWidgets = new Array();
		}

		static public function getInstance():WidgetManager
		{
			if (!instance)
				instance = new WidgetManager();
			return instance;
		}
		
		//打开鼠标悬浮窗口
		public function popOutMouseOverMessage(widget:Sprite):void
		{
			closeMouseOverMessage();
			mouseOverMessage = widget;
			SceneManager.getInstance().currentScene.addChild(widget);
		}
		
		//关闭鼠标悬浮窗口
		public function closeMouseOverMessage():void
		{
			if (mouseOverMessage != null && mouseOverMessage.parent != null)
				mouseOverMessage.parent.removeChild(mouseOverMessage);
			mouseOverMessage = null;
		}
		
		public function getWidget(DialogClass:Class):DisplayObject
		{
			var scene:BasicScene = SceneManager.getInstance().currentScene;
			for (var i:int = 0; i < scene.numChildren; i++)
			{
				var widget:DisplayObject = scene.getChildAt(i);
				if (widget is DialogClass)
					return widget;
			}
			return null;
		}
		
		public function popOut(widgets:Array, exclusive:Boolean = false, center:Boolean = false):void
		{
			if (exclusive)
			{
				closeCenterWidgets();
				exclusiveWidgets = new Array();
			}
			for (var i:int = 0; i < widgets.length; i++)
			{
				var widget:Sprite = widgets[i];
				if (center)
				{
					widget.x = (BFont.stageWidth - widget.width) / 2;
					widget.y = (BFont.stageHeight - widget.height) / 2;
				}
				SceneManager.getInstance().currentScene.addChild(widget);
				if (exclusive)
					exclusiveWidgets.push(widget);
			}
			BSound.getInstance().playEffect("SoundButton1");
		}
		
		public function closeCenterWidgets():void
		{
			if (exclusiveWidgets != null)
			{
				for (var i:int = 0; i < exclusiveWidgets.length; i++)
				{
					var widget:Sprite = exclusiveWidgets[i];
					if (widget != null && widget.parent != null)
					{
						widget.parent.removeChild(widget);
						//Fix Bug:通过WigetManager关闭科技塔时物品没有放下 
						if (widget is TechTower)
						{
							(widget as TechTower).removeAll();
						}
						delete exclusiveWidgets[i];
					}
				}
				exclusiveWidgets = null;
			}
		}
	}
}